﻿<template>
  <div>
    <el-dialog v-drag :title = 'dialogSelectTitle' :visible.sync = 'dialogSelectVisible' :width = 'dialogWidth'
    :before-close = 'closeDialog' append-to-body :close-on-click-modal = 'false' :close-on-press-escape = 'false'>
      <el-form ref='ruleForm' :model= 'formModel' v-loading = 'loading' :element-loading-text = 'loadingText'>
        <el-form-item :label='dialogLabel' label-position = 'top'>
          <!-- 下拉列表(单选) -->
          <el-select :class = "isDisabled ? 'select_disabled' : ''" v-model='formModel.editData' filterable v-if = "uiType === 'singleSelect'" clearable placeholder='请选择'>
            <el-option :disabled = "isDisabled" v-for='(selectItem, select$Index) in selectOption' :key = 'select$Index' :label = "selectItem.label" :value = 'selectItem.value'></el-option>
          </el-select>
          <!-- 下拉列表(多选) -->
          <el-select :class = "isDisabled ? 'select_disabled' : ''" v-model='formModel.editData' filterable multiple v-if = "uiType === 'multiSelect'" clearable placeholder='请选择'>
            <el-option :disabled = "isDisabled" v-for='(selectItem, select$Index) in selectOption' :key = 'select$Index' :label = "selectItem.label" :value = 'selectItem.value'></el-option>
          </el-select>
          <!-- 日期时间 -->
          <el-date-picker value-format='yyyy-MM-dd HH:mm:ss' format = 'yyyy-MM-dd HH:mm:ss' :disabled = "isDisabled" v-model='formModel.editData'
          v-else-if = "uiType === 'datetime'" type = "datetime" placeholder="选择日期时间"></el-date-picker>
           <!-- 日期 -->
          <el-date-picker value-format='yyyy-MM-dd' :disabled = "isDisabled" format = 'yyyy-MM-dd' v-model='formModel.editData'
          v-else-if = "uiType === 'date'" type = "date" placeholder="选择日期"></el-date-picker>
           <!-- 时间 -->
          <el-time-picker value-format='HH:mm:ss' :disabled = "isDisabled" format = 'HH:mm:ss' v-model='formModel.editData'
          v-else-if = "uiType === 'time'" placeholder="选择时间"></el-time-picker>
          <!-- 开关 -->
          <el-switch :disabled = "isDisabled" v-else-if="uiType === 'switch'" v-model='formModel.editData'></el-switch>
          <!-- 多行文本 -->
          <el-input type = "textarea" :disabled = "isDisabled" v-else-if="uiType === 'textarea'" v-model='formModel.editData'
          placeholder = '请输入' autosize></el-input>
          <!-- 富文本 -->
          <div v-else-if="uiType === 'richText'">
            <br>
             <Tinymce-Component ref = "myTinymce" :disabled = "isDisabled"
            :defaultValue.sync = 'formModel.editData' :showTinymce = 'showEditTableDataDialog'></Tinymce-Component>
          </div>
          <!-- 文件 -->
          <div v-else-if = "uiType === 'file' || uiType === 'readFile'">
            <br>
            <el-upload ref='upload' :action='actionUrl' :auto-upload="true" :file-list = 'fileList' drag
            :before-remove = 'removeUpload' :on-preview = "handlePictureCardPreview" :class = "(isDisabled || uiType === 'readFile') ? 'hiddenUploadInput' : ''"
            :http-request = "submitUpload">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
            <span v-if = "(isDisabled || uiType === 'readFile') && !formModel.editData.length">暂无文件</span>
          </div>
          <!-- 普通文本时 -->
          <el-input :disabled = "isDisabled" v-model='formModel.editData' v-else-if = "uiType === 'input'" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item v-show = "(!isDisabled && uiType !== 'readFile')" class='form_noLeftMargin'>
          <el-button type="info" @click="closeDialog">取 消</el-button>
          <el-button type = "primary" @click = "defineExport" v-show = "uiType === 'RichText'">导 出</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </el-form-item>
        <el-form-item v-show = "(isDisabled && uiType === 'RichText')" class='form_noLeftMargin'>
          <el-button type = "primary" @click = "defineExport">导 出</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import TinymceComponent from '@/components/Tinymce/TinymceComponent'
export default {
  props: ['clickIndex', 'widgetObject', 'clickName', 'currentModels', 'editClickRow', 'showEditTableDataDialog'],
  components: { TinymceComponent },
  data () {
    return {
      dialogSelectVisible: false,
      dialogSelectTitle: '编辑字段信息',
      formModel: {
        editData: null
      },
      dialogLabel: '',
      uiType: '',
      isDisabled: false,
      // 下拉框的选项
      selectOption: [],
      loading: false,
      loadingText: '数据加载中',
      // 上传文件部分
      actionUrl: `${$URL.IMG_UPLOAD_URL}`,
      fileList: [],
      fileReader: '',
      myDataModel: [],
      // 当前执行事件的集合
      currentEventsObj: null,
      // 事件的请求和响应的数据----api的键/页面展示的键/值/事件编号
      // inputArray----apiKey/pageKey/eventNo
      // outputArray----apiKey/pageKey/value/eventNo
      pagePrimaryObj: {
        inputArray: [],
        outputArray: []
      },
      // 当前字段的联动信息
      currentLinkage: null,
      linkageElementsData: null,
      // 可编辑的表格中下拉框事件的集合
      editTableSelectArray: []
    }
  },
  mounted () {
    if (!window.FileReader) {
      this.$message({
        message: '您的浏览器不支持 FileReader API',
        type: 'warning'
      })
    } else {
      this.fileReader = new FileReader()
    }
  },
  computed: {
    dialogWidth () {
      if (this.uiType === 'RichText') {
        return '95%'
      } else {
        return '35%'
      }
    }
  },
  methods: {
    // 富文本编辑器的导出功能
    defineExport () {
      this.$refs.myTinymce.exportWordMethod()
    },
    // 初始化页面信息
    initPage () {
      this.currentEventsObj = null
      this.currentLinkage = null
      this.linkageElementsData = null
      this.pagePrimaryObj = {
        inputArray: [],
        outputArray: []
      }
      if (this.widgetObject && this.widgetObject.tableColumn.length) {
        // 当前页面的状态
        this.isDisabled = this.widgetObject.options.disabled
        // 获取页面展示的数据
        this.formModel.editData = this.currentModels[this.widgetObject.model][this.clickIndex][this.clickName]
        // 获取点击的字段的类型
        for (let i = 0; i < this.widgetObject.tableColumn.length; i++) {
          let currentItem = this.widgetObject.tableColumn[i]
          if (currentItem.linkageOption) {
            this.currentLinkage = currentItem.linkageOption
          }
          if (currentItem.indexName === this.clickName) {
            this.uiType = currentItem.uiType
            // label展示的内容
            this.dialogLabel = currentItem.text + '：'
            // 标题
            this.dialogSelectTitle = (this.isDisabled || this.uiType === 'readFile') ? '查看（' + currentItem.text + '）字段详细' : '编辑（' + currentItem.text + '）字段内容'
            // 如果是下拉框，需要获取下拉框的数据源
            if (this.uiType === 'singleSelect' || this.uiType === 'multiSelect') {
              this.selectOption = []
              if (currentItem.selectOption.remote && currentItem.selectOption.remoteFunc) {
                if (currentItem.selectOption.inputDic && currentItem.selectOption.outputDic) {
                  this.currentEventsObj = {
                    inputDic: currentItem.selectOption.inputDic,
                    outputDic: currentItem.selectOption.outputDic,
                    eventsNo: currentItem.selectOption.remoteFunc
                  }
                }
                // 服务器上的数据
                this.getEventsInfoByEventNo(currentItem.selectOption.remoteFunc, currentItem.selectOption.remoteProps, null)
              } else {
                // 静态数据
                this.selectOption = currentItem.selectOption.staticOption
              }
            } else if (this.uiType === 'switch') {
              if (!this.currentModels[this.widgetObject.model][this.clickIndex][this.clickName]) {
                this.formModel.editData = false
              }
            } else if (this.uiType === 'file' || this.uiType === 'readFile') {
              this.fileList = []
              this.myDataModel = (this.formModel.editData && this.formModel.editData.length) ? this.formModel.editData : []
              if (this.formModel.editData && this.formModel.editData.length) {
                this.formModel.editData.forEach(item => {
                  if (item) {
                    let obj = {
                      name: item.slice(item.indexOf('/name/') + 6),
                      url: item
                    }
                    this.fileList.push(obj)
                  }
                })
              }
            } else if (this.uiType === 'date' || this.uiType === 'datetime' || this.uiType === 'time') {
              if (this.formModel.editData) {
                this.formModel.editData = new Date(this.formModel.editData)
              }
            }
            break
          }
        }
      }
    },
    // 根据事件编号获取该事件的key值
    getEventKeyByEventNo (targetEventNo) {
      // 每次将this.pagePrimaryObj.inputArray清空
      this.pagePrimaryObj.inputArray = []
      if (this.currentEventsObj && !this.$isEmptyObject(this.currentEventsObj) && this.currentEventsObj.inputDic) {
        // 输入的参数格式为：api中的键名 = 页面展示的键名
        for (let i = 0; i < this.currentEventsObj.inputDic.length; i++) {
          if (this.currentEventsObj.inputDic[i].inputKey.indexOf('=') !== -1) {
            let dicInputArray = this.currentEventsObj.inputDic[i].inputKey.split('=')
            let obj = {
              apiKey: dicInputArray[0],
              pageKey: dicInputArray[1],
              eventNo: targetEventNo
            }
            this.pagePrimaryObj.inputArray.push(obj)
          }
        }
      }
      // 获取输出的参数
      if (this.currentEventsObj && !this.$isEmptyObject(this.currentEventsObj) && this.currentEventsObj.outputDic) {
        // 输出的参数格式为： 页面展示的键名 = api中的键名
        for (let i = 0; i < this.currentEventsObj.outputDic.length; i++) {
          if (this.currentEventsObj.outputDic[i].outputKey.indexOf('=') !== -1) {
            let dicOutputArray = this.currentEventsObj.outputDic[i].outputKey.split('=')
            let hadPushed = false
            // 判断该事件的输出参数是否已经加入过一次
            if (this.pagePrimaryObj.outputArray.length) {
              for (let i = 0; i < this.pagePrimaryObj.outputArray.length; i++) {
                if (targetEventNo === this.pagePrimaryObj.outputArray[i].eventNo && this.pagePrimaryObj.outputArray[i].apiKey === dicOutputArray[1] && this.pagePrimaryObj.outputArray[i].pageKey === dicOutputArray[0]) {
                  hadPushed = true
                }
              }
            }
            if (!hadPushed) {
              let obj = {
                apiKey: dicOutputArray[1],
                pageKey: dicOutputArray[0],
                value: null,
                eventNo: targetEventNo
              }
              this.pagePrimaryObj.outputArray.push(obj)
            }
          }
        }
      }
    },
    // 根据事件编号获取事件的详细
    getEventsInfoByEventNo (eventItemNo, valueObj, triggerModels) {
      this.loading = true
      this.loadingText = '数据加载中'
      // 获取该事件的key值
      this.getEventKeyByEventNo(eventItemNo)
      // 获取事件的详细
      this.$get('/events4dform/' + eventItemNo).then(data => {
        let dataInfo = data.data.result
        if (dataInfo.code === 'failed') {
          this.$message({
            message: dataInfo.msg,
            type: 'warning'
          })
          this.loading = false
        }
        if (dataInfo.code === 'success') {
          let currentEventInfo = {
            no: dataInfo.data.no,
            name: dataInfo.data.name,
            category: dataInfo.data.category,
            request_parameters: dataInfo.data.request_parameters,
            response_data: dataInfo.data.response_data
          }
          let parametersObj = JSON.parse(dataInfo.data.request_parameters)
          let isLocalEvent = false
          // 判断事件的类型，RequestUrl是以~开头的是本地事件，否则是http事件
          if (parametersObj.RequestUrl.indexOf('~') === 0) {
            isLocalEvent = true
          }
          this.changeEventsInfoBeforeSubmit(eventItemNo, currentEventInfo, isLocalEvent, valueObj, triggerModels)
        }
      }).catch(error => {
        this.loading = false
        this.$message({
          message: error,
          type: 'warning'
        })
      })
    },
    // 修改输入参数的公共方法
    getInputParamsMethods (pageKey, submitData) {
      let inputKeyValue = ''
      if (pageKey.indexOf('@') === 0) {
        inputKeyValue = pageKey.slice(1)
      } else if (pageKey === '$_login_id') {
        inputKeyValue = this.$store.state.nameId
      } else if (pageKey === '$_login_name' || pageKey === '$_user_name') {
        inputKeyValue = this.$store.state.userName
      } else if (pageKey === '$_now') {
        inputKeyValue = new Date()
      } else if (pageKey === '$_FormKey') {
        inputKeyValue = this.dynamicUid
      } else if (pageKey === '$_PrimaryKey') {
        inputKeyValue = this.workFlowParams.primaryKey
      } else if (pageKey === '$_Status') {
        inputKeyValue = this.workFlowParams.status
      } else if (pageKey === '$_user_no') {
        inputKeyValue = this.$store.state.userNo
      } else {
        for (let sKey in submitData) {
          if (pageKey === sKey) {
            inputKeyValue = submitData[sKey]
            break
          }
        }
      }
      return inputKeyValue
    },
    // 修改事件的参数----主要是需要修改事件path、search、postData等参数
    changeEventsInfoBeforeSubmit (eventItemNo, currentEventInfo, isLocalEvent, valueObj, triggerModels) {
      // 定一个空对象获取this.models和点击传入的值
      let submitData = {}
      if (this.currentModels && !this.$isEmptyObject(this.currentModels)) {
        Object.assign(submitData, this.currentModels)
      }
      if (this.editClickRow && !this.$isEmptyObject(this.editClickRow)) {
        Object.assign(submitData, this.editClickRow)
      }
      // 获取触发事件的parameters
      let evalParamters = {}
      if (this.pagePrimaryObj.inputArray.length) {
        this.pagePrimaryObj.inputArray.forEach(item => {
          // 找到该事件对应的参数
          if (item.eventNo === eventItemNo) {
            // 判断apiKey是否是 Query.key的结构（Query表示的是字段名，key表示的是该对象中的一个属性）
            if (item.apiKey.indexOf('.') !== -1) {
              let apiObjString = item.apiKey.split('.')
              // 需要先判断该对象是否已经存在于evalParamters中
              if (Object.keys(evalParamters).indexOf(apiObjString[0]) === -1) {
                evalParamters[apiObjString[0]] = {}
              }
              evalParamters[apiObjString[0]][apiObjString[1]] = this.getInputParamsMethods(item.pageKey, submitData)
            } else {
              evalParamters[item.apiKey] = this.getInputParamsMethods(item.pageKey, submitData)
            }
          }
        })
      }
      let toEvalMethodJsonString = this.$isEmptyObject(evalParamters) ? '' : evalParamters
      this.triggerEventMethod(eventItemNo, currentEventInfo, isLocalEvent, valueObj, submitData, toEvalMethodJsonString, triggerModels)
    },
    // 触发事件
    triggerEventMethod (eventItemNo, currentEventInfo, isLocalEvent, valueObj, submitData, toEvalMethodJsonString, triggerModels) {
      if (isLocalEvent) {
        this.$post('/events4dform/' + eventItemNo + '/eval', {
          this_data: '',
          parameters: toEvalMethodJsonString
        }).then(data => {
          let dataInfo = data.data.result
          this.loading = false
          if (dataInfo.code === 'failed') {
            this.$message({
              message: dataInfo.msg,
              type: 'warning'
            })
          } else if (dataInfo.code === 'success') {
            this.afterEval(valueObj, dataInfo.data, eventItemNo, triggerModels)
          }
        }).catch(error => {
          this.loading = false
          this.$message({
            message: error,
            type: 'warning'
          })
        })
      } else {
        let requestObj = JSON.parse(currentEventInfo.request_parameters)
        if (!this.$isEmptyObject(requestObj) && requestObj.RequestUrl && requestObj.RequestMethod) {
          let axiosUrl = requestObj.RequestUrl
          // 改变path
          if (requestObj.RequestPath && !this.$isEmptyObject(requestObj.RequestPath)) {
            // 获取请求的url中的path---将url中的变量的改为获取到的值
            for (let pathKey in requestObj.RequestPath) {
              for (let modelKey in submitData) {
                if (pathKey === modelKey) {
                  axiosUrl = axiosUrl.replace('{' + pathKey + '}', submitData[pathKey])
                }
              }
            }
          }
          // 修改query的值
          let axiosQuery = {}
          if (requestObj.RequestQueryString && !this.$isEmptyObject(requestObj.RequestQueryString) && toEvalMethodJsonString) {
            for (let searchKey in requestObj.RequestQueryString) {
              for (let parametersKey in toEvalMethodJsonString) {
                if (searchKey === parametersKey) {
                  axiosQuery[searchKey] = toEvalMethodJsonString[parametersKey]
                }
              }
            }
          }
          // 修改postData的值
          let axiosPostData = {}
          if (requestObj.RequestPostData && !this.$isEmptyObject(requestObj.RequestPostData) && toEvalMethodJsonString) {
            for (let postKey in requestObj.RequestPostData) {
              for (let parametersKey in toEvalMethodJsonString) {
                if (postKey === parametersKey) {
                  axiosPostData[postKey] = toEvalMethodJsonString[parametersKey]
                }
              }
            }
          }
          axios({
            url: axiosUrl,
            method: requestObj.RequestMethod,
            // headers: requestObj.RequestHeader,
            data: axiosPostData,
            params: axiosQuery
          }).then(data => {
            let dataInfo = data.data.result
            this.loading = false
            if (dataInfo.code === 'failed') {
              this.$message({
                message: dataInfo.msg,
                type: 'error'
              })
            } else if (dataInfo.code === 'success') {
              this.afterEval(valueObj, dataInfo.data, eventItemNo, triggerModels)
            }
          }).catch(error => {
            this.loading = false
            this.$message({
              message: error,
              type: 'warning'
            })
          })
        }
      }
    },
    // 对事件触发后的结果进行处理
    afterEval (valueObj, dataResult, eventItemNo, triggerModels) {
      if (triggerModels && !this.$isEmptyObject(triggerModels)) {
        // 如果是联动的元素触发下拉时
        if (dataResult && !this.$isEmptyObject(valueObj)) {
          // 根据输出词典表，修改dataInfo.data中的值
          for (let i = 0; i < this.pagePrimaryObj.outputArray.length; i++) {
            if (this.pagePrimaryObj.outputArray[i].eventNo === eventItemNo) {
              for (let i = 0; i < dataResult.length; i++) {
                for (let dKey in dataResult[i]) {
                  // 如果返回的值的某一个键设置的词典表，则将该词典表对于的pageKey设置对于的值并存在返回值的集合中
                  if (this.pagePrimaryObj.outputArray[i].apiKey === dKey) {
                    this.$set(dataResult[i], this.pagePrimaryObj.outputArray[i].pageKey, dataResult[i][dKey])
                  }
                }
              }
            }
          }
          let select = dataResult.map(item => {
            return {
              value: item[valueObj.value],
              label: item[valueObj.label]
            }
          })
          for (let i = 0; i < select.length; i++) {
            if (select[i].value === triggerModels.dataObject[triggerModels.editTableItem.indexName]) {
              this.$set(triggerModels.dataObject, triggerModels.editTableItem.indexName + '_$SHOW', select[i].label)
              break
            }
          }
          // 判断还有没有事件需要执行
          let hadUnTrugger = false
          for (let i = 0; i < this.editTableSelectArray.length; i++) {
            if (!this.editTableSelectArray[i].isTrigger) {
              hadUnTrugger = true
              if (this.editTableSelectArray[i].editTableItem.selectOption.inputDic && this.editTableSelectArray[i].editTableItem.selectOption.outputDic) {
                this.currentEventsObj = {
                  inputDic: this.editTableSelectArray[i].editTableItem.selectOption.inputDic,
                  outputDic: this.editTableSelectArray[i].editTableItem.selectOption.outputDic,
                  eventsNo: this.editTableSelectArray[i].editTableItem.selectOption.remoteFunc
                }
              }
              this.getEventsInfoByEventNo(this.editTableSelectArray[i].editTableItem.selectOption.remoteFunc, this.editTableSelectArray[i].editTableItem.selectOption.remoteProps, this.editTableSelectArray[i])
              this.editTableSelectArray[i].isTrigger = true
              break
            }
          }
          if (!hadUnTrugger) {
            if (!this.$isEmptyObject(triggerModels.dataObject)) {
              this.linkageElementsData = JSON.parse(JSON.stringify(triggerModels.dataObject))
            }
            // 修改完数据后关闭弹窗
            this.handleSubmitPassToParent()
          }
        }
      } else {
        // 正常的获取事件
        if (dataResult && valueObj !== 'changeClickRowData' && !this.$isEmptyObject(valueObj)) {
          // 触发的是获取select的数据源时
          this.selectOption = dataResult.map(item => {
            return {
              value: item[valueObj.value],
              label: item[valueObj.label]
            }
          })
        } else {
          // 联动的情况
          if (dataResult && valueObj === 'changeClickRowData') {
            let dataObj = dataResult
            if (this.$isArray(dataResult)) {
              dataObj = dataResult[0]
            }
            // 根据输出词典表，修改dataObj中的值
            for (let i = 0; i < this.pagePrimaryObj.outputArray.length; i++) {
              if (this.pagePrimaryObj.outputArray[i].eventNo === eventItemNo) {
                for (let dKey in dataObj) {
                  // 如果返回的值的某一个键设置的词典表，则将该词典表对于的pageKey设置对于的值并存在返回值的集合中
                  if (this.pagePrimaryObj.outputArray[i].apiKey === dKey) {
                    this.$set(dataObj, this.pagePrimaryObj.outputArray[i].pageKey, dataObj[dKey])
                  }
                }
              }
            }
            // 如果设置了联动元素
            let dataObject = {}
            this.editTableSelectArray = []
            if (this.currentLinkage.linkageElements && this.currentLinkage.linkageElements.length) {
              this.currentLinkage.linkageElements.forEach(item => {
                for (let dKey in dataObj) {
                  if (item === dKey) {
                    dataObject[item] = dataObj[item]
                  }
                }
                // 判断关联的字段是否是下拉类型的
                for (let i = 0; i < this.widgetObject.tableColumn.length; i++) {
                  if (item === this.widgetObject.tableColumn[i].indexName) {
                    if (this.widgetObject.tableColumn[i].uiType === 'singleSelect' || this.widgetObject.tableColumn[i].uiType === 'multiSelect') {
                      if (this.widgetObject.tableColumn[i].selectOption.remote && this.widgetObject.tableColumn[i].selectOption.remoteFunc && !this.$isEmptyObject(this.widgetObject.tableColumn[i].selectOption.remoteProps)) {
                        let obj = {
                          isTrigger: false,
                          editTableItem: this.widgetObject.tableColumn[i],
                          dataObject: dataObject
                        }
                        this.editTableSelectArray.push(obj)
                      } else if (!this.widgetObject.tableColumn[i].selectOption.remote && this.widgetObject.tableColumn[i].selectOption.staticOption.length) {
                        // 为models中添加一个_$SHOW的字段
                        for (let showKey = 0; showKey < this.widgetObject.tableColumn[i].selectOption.staticOption.length; showKey++) {
                          if (this.widgetObject.tableColumn[i].selectOption.staticOption[showKey].value === dataObj[item]) {
                            dataObject[item + '_$SHOW'] = this.widgetObject.tableColumn[i].selectOption.staticOption[showKey].label
                            break
                          }
                        }
                      }
                    }
                    break
                  }
                }
              })
            }
            // 判断关联的元素是否是下拉需要请求接口
            if (this.editTableSelectArray.length) {
              let currentItem = this.editTableSelectArray[0].editTableItem
              if (currentItem.selectOption.inputDic && currentItem.selectOption.outputDic) {
                this.currentEventsObj = {
                  inputDic: currentItem.selectOption.inputDic,
                  outputDic: currentItem.selectOption.outputDic,
                  eventsNo: currentItem.selectOption.remoteFunc
                }
              }
              // 服务器上的数据
              this.getEventsInfoByEventNo(currentItem.selectOption.remoteFunc, currentItem.selectOption.remoteProps, this.editTableSelectArray[0])
              this.editTableSelectArray[0].isTrigger = true
            } else {
              if (!this.$isEmptyObject(dataObject)) {
                this.linkageElementsData = JSON.parse(JSON.stringify(dataObject))
              }
              // 修改完数据后关闭弹窗
              this.handleSubmitPassToParent()
            }
          }
        }
      }
    },
    // 上传文件相关的
    // 点击下载的方法
    handlePictureCardPreview (file) {
      this.$confirm('确定要下载该文件么', '提示', {
        showClose: false,
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonClass: 'el-button--info',
        cancelButtonText: '取消'
      }).then(() => {
        this.loadingText = '文件下载中...'
        this.loading = true
        this.getFileBasicInfo(file.url, 'download')
      }).catch(() => {})
    },
    // 上传文件移除
    removeUpload (file) {
      this.$confirm('确定要移除该文件么', '提示', {
        showClose: false,
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonClass: 'el-button--info',
        cancelButtonText: '取消'
      }).then(() => {
        if (this.myDataModel && this.myDataModel.length) {
          this.myDataModel.forEach((item, index) => {
            if (item === file.url) {
              this.myDataModel.splice(index, 1)
            }
          })
        }
        if (this.fileList.length) {
          this.fileList.forEach((item, index) => {
            if (item.url === file.url) {
              this.fileList.splice(index, 1)
            }
          })
        }
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      }).catch(() => {
      })
      return false
    },
    submitUpload (options) {
      this.loading = true
      this.loadingText = '文件上传中'
      let file = options.file
      let filename = file.name
      let fileLength = file.size
      if (file) {
        this.fileReader.readAsDataURL(file)
      }
      this.fileReader.onload = () => {
        let base64Str = this.fileReader.result
        /* global $URL */
        axios({
          url: $URL.IMG_UPLOAD_URL + '/fileset/upload',
          method: 'post',
          data: {
            file_name: filename,
            file_length: fileLength,
            file_content: base64Str.split(',')[1]
          }
        }).then(data => {
          this.loading = false
          if (data.data.result.code === 'success') {
            this.$message({
              message: '上传成功',
              type: 'success'
            })
            let obj = {
              name: filename,
              url: data.data.result.link_url + '/name/' + filename
            }
            this.fileList.push(obj)
            this.myDataModel.push(data.data.result.link_url + '/name/' + filename)
          } else {
            this.$message({
              message: data.data.result.msg,
              type: 'error'
            })
          }
        }).catch(error => {
          this.loading = false
          console.log(error)
        })
      }
    },
    // 根据url获取到文件的基本信息
    getFileBasicInfo (fileUrl, download) {
      let downUrl = ''
      if (fileUrl) {
        downUrl = fileUrl.slice(0, fileUrl.indexOf('/name/'))
        axios({
          url: downUrl,
          method: 'get'
        }).then(data => {
          let dataInfo = data.data.result
          this.loading = false
          if (dataInfo.code === 'success') {
            if (download && download === 'download') {
              let content = decodeURIComponent(dataInfo.file)
              let blobContent = this.toBlob(content, dataInfo.filetype)
              this.downloadblob(blobContent, dataInfo.filename)
            }
          } else if (dataInfo.code === 'failed') {
            this.$message({
              message: dataInfo.msg,
              type: 'error'
            })
          }
        }).catch(error => {
          this.loading = false
          console.log(error)
        })
      } else {
        this.$message({
          message: '没有获取到本文件的下载地址',
          type: 'warning'
        })
      }
    },
    // 下载文件到本地
    downloadblob (blobcontent, filename) {
      if ('msSaveOrOpenBlob' in navigator) {
        // Microsoft Edge and Microsoft Internet Explorer 10-11
        window.navigator.msSaveOrOpenBlob(blobcontent, filename)
      } else {
        // 创建隐藏的可下载链接
        var eleLink = document.createElement('a')
        eleLink.download = filename
        eleLink.style.display = 'none'
        // 字符内容转变成blob地址
        eleLink.href = URL.createObjectURL(blobcontent)
        // 触发点击
        document.body.appendChild(eleLink)
        eleLink.click()
        // 然后移除
        document.body.removeChild(eleLink)
      }
    },
    // 将base64装为文件
    toBlob (base64str, filetype) {
      let bytes = window.atob(base64str)
      let n = bytes.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bytes.charCodeAt(n)
      }
      return new Blob([u8arr], {type: filetype})
    },
    closeDialog () {
      this.$refs.ruleForm.clearValidate()
      this.$emit('giveUp')
      if (this.uiType === 'File') {
        this.$refs.upload.abort()
        this.$refs.upload.clearFiles()
      }
    },
    // 点击确定按钮时---需要判断是否为联动字段
    handleSubmit () {
      if (this.currentLinkage && this.currentLinkage.isLinkage && this.formModel.editData) {
        // 改变editClickRow中对应的值
        this.editClickRow[this.clickName] = this.formModel.editData
        this.linkageElementsData = null
        if (this.currentLinkage.linkageType === 'eventRender') {
          if (!this.currentLinkage.linkageEvents) {
            this.$message({
              message: '该字段为联动字段(数据渲染模式)，但尚未设置联动的方法，请前往资源管理进行设置',
              type: 'warning'
            })
          } else {
            this.currentEventsObj = {
              inputDic: this.currentLinkage.inputDic,
              outputDic: this.currentLinkage.outputDic,
              eventsNo: this.currentLinkage.linkageEvents
            }
            this.getEventsInfoByEventNo(this.currentLinkage.linkageEvents, 'changeClickRowData', null)
          }
        } else if (this.currentLinkage.linkageType === 'expressionRender' && Object.keys(this.currentLinkage).indexOf('expressionArray') !== -1) {
          if (!this.currentLinkage.expressionArray.length) {
            let msg = '该字段为联动字段(数据计算模式)，但尚未设置计算表达式或计算字段（或表达式格式不正确），请前往资源管理进行设置'
            this.$message({
              message: msg,
              type: 'warning'
            })
          } else {
            this.currentLinkage.expressionArray.forEach(item => {
              if (item.expression.indexOf('=') !== -1) {
                let submitData = {}
                if (this.currentModels && !this.$isEmptyObject(this.currentModels)) {
                  Object.assign(submitData, this.currentModels)
                }
                if (this.editClickRow && !this.$isEmptyObject(this.editClickRow)) {
                  Object.assign(submitData, this.editClickRow)
                }
                let expression = item.expression.split('=')
                // 替换表达式中的符号
                let expressionSymolReplace = expression[1].replace(/\{\+\}/g, '+').replace(/\{-\}/g, '-').replace(/\{\/\}/g, '/').replace(/\{\*\}/g, '*').replace(/\{EQ\}/g, '=')
                // 通过计算字段，修改表达式中对应的值
                for (let i = 0; i < item.expressionElements.length; i++) {
                  let val = submitData[item.expressionElements[i]]
                  // 当该表达式的值没有时，默认设置为空
                  let replaceVal = 0
                  if (val) {
                    replaceVal = val
                    if (typeof (val) === 'string') {
                      replaceVal = '"' + val + '"'
                    }
                    // 值小于0时，避免出现--，/-等情况
                    if (val < 0) {
                      replaceVal = '(' + val + ')'
                    }
                  }
                  expressionSymolReplace = expressionSymolReplace.replace(new RegExp('{' + item.expressionElements[i] + '}', 'g'), replaceVal)
                }
                // 通过表达式获取到计算后的值
                if (expressionSymolReplace) {
                  let dataObj = {}
                  dataObj[expression[0]] = this.$selfdefineEval(expressionSymolReplace)
                  // this.linkageElementsData = JSON.parse(JSON.stringify(dataObj))
                  if (!this.linkageElementsData) {
                    this.linkageElementsData = {}
                  }
                  this.$set(this.linkageElementsData, expression[0], this.$selfdefineEval(expressionSymolReplace))
                }
              }
            })
          }
          this.handleSubmitPassToParent()
        }
      } else {
        this.handleSubmitPassToParent()
      }
    },
    // 点击确定传参的方法
    handleSubmitPassToParent () {
      let toParents = {
        index: this.clickIndex,
        name: this.clickName,
        widgetObject: this.widgetObject,
        data: this.formModel.editData,
        data_show: '',
        uiType: this.uiType,
        linkageElementsData: this.linkageElementsData
      }
      if (this.formModel.editData && (this.uiType === 'singleSelect' || this.uiType === 'multiSelect') && this.selectOption.length) {
        this.selectOption.forEach(item => {
          if (item.value === this.formModel.editData) {
            toParents.data_show = item.label
          }
        })
      }
      if (this.uiType === 'file') {
        toParents.data = this.myDataModel
      }
      this.$refs.ruleForm.clearValidate()
      this.$emit('sureEditTableData', toParents)
    }
  },
  watch: {
    showEditTableDataDialog: {
      handler: function (val, oldVal) {
        this.dialogSelectVisible = val
        if (val) {
          this.initPage()
        }
      },
      deep: true
    }
  }
}
</script>

<style lang='scss' scoped>
#myMap{
  width:100%;
  height:400px;
}
#pickImgContent{
  width:100%;
  height:500px;
  overflow: auto;
  position:relative;
  img{
    cursor:pointer;
  }
  .locationIcon{
    position:absolute;
    width:30px;
    height:30px;
    text-align:center;
    line-height:30px;
    i{
      font-size:30px;
      color:red;
    }
  }
}
.outContent{
  position:relative;
  width:100%;
  height:500px;
}
.innerContent{
  position:absolute;
  width:100%;
  left:0;
  top:0;
  z-index:1000;
}
</style>
